package com.example.zjhuojback.controller;

import com.example.zjhuojback.entity.*;
import com.example.zjhuojback.service.ContestService;
import com.example.zjhuojback.service.UserService;
import org.json.JSONObject;
import com.example.zjhuojback.common.Result;
import com.example.zjhuojback.service.ProblemService;
import com.example.zjhuojback.service.SubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/problem")
public class ProblemController {
    @Autowired
    private ProblemService problemService;
    @Autowired
    private RestTemplate restTemplate;  // 注入 RestTemplate
    @Autowired
    private SubmissionService submissionService;
    @Autowired
    private UserService userService;
    @Autowired
    private ContestService contestService;
    /*查询全部题目*/
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Problem> problemList = problemService.selectAll();
        return Result.success(problemList);
    }
    @GetMapping("/selectAllAdmin")
    public Result selectAllAdmin() {
        List<Problem> problemList = problemService.selectAllAdmin();
        return Result.success(problemList);
    }
    @GetMapping("/selectById")
    public Result selectById(Integer id) {
        Problem problem = problemService.selectById(id);
        return Result.success(problem);
    }

    // 假设是一个 GET 请求，判断用户是否通过某道题
    @GetMapping("/{problemId}/user/{userName}/status")
    public Result getUserProblemStatus(
            @PathVariable String userName,
            @PathVariable int problemId) {
        // 查询该用户的题目提交状态
        boolean status = problemService.getUserProblemStatus(userName, problemId);
        if (status) return Result.success();        // 做过这题
        else return Result.error();             // 没做过
    }


    /* 通过判题系统 API 执行代码 */
    @PostMapping("/submitCode")
    public Result submitCode(@RequestBody Code problem) {
        // 获取前端传递的值
        String username = problem.getUserName(); // 提交者用户名
        String name = problem.getName();         // 提交者姓名
        Integer problemId = problem.getId();     // 题目ID
        String language = problem.getLanguage(); // 提交的编程语言
        LocalDateTime submitTime = LocalDateTime.now();
        // 调用外部接口（判题系统）
        String result = restTemplate.postForObject(
                "http://123.56.85.41:8081/executeCode/", // 外部 API 地址
                problem,   // 传递请求体
                String.class        // 响应体类型
        );
        // 判断程序运行结果
        String res = "答案错误";
        boolean ac = false;
        Integer memoryUsage = 0;
        Integer timeUsage = 0;
        if (result.contains("\"status\":1")) { ac = true; res = "正确";}
        else if (result.contains("\"status\":2")) { res = "编译错误";}
        try {
            // 解析返回的 JSON 字符串
            JSONObject resultJson = new JSONObject(result);
            // 提取时间和内存数据
            timeUsage = resultJson.optInt("timeUsage", 0);  // 获取时间消耗
            memoryUsage = resultJson.optInt("memoryUsage", 0);  // 获取内存占用
        } catch (Exception e) {
            e.printStackTrace();  // 输出错误
        }
        // 增加题目的AC数量
        problemService.updateSubmit(ac, problemId);

        // 用户第一次AC这道题则添加数据进stattus表中
        if (problem.getStatus() == 1 && ac) {
            problemService.insertStatus(username, problemId);
        }

        // 更新用户过题和ac数据
        userService.updateSubmit(problem.getStatus(), ac, username);

        // 保存提交记录到数据库
        submissionService.saveSubmission(username, name, problemId, res, memoryUsage, timeUsage, language, problem.getCode(),submitTime);

        Contest contest = contestService.selectById(problem.getContestId());
        // 如果在比赛进行中提交题目
        if (problem.getContestStatus() == 1) {
            if (!submitTime.isBefore(contest.getStartTime()) && !submitTime.isAfter(contest.getEndTime())) {
                contestService.insertContestSubmission(problem.getContestId(), problemId, problem.getUserId(), ac, submitTime);
            } else contestService.updateStatus(contest.getId(),2);
        }

        return Result.success(res);
    }



    /*删除题目*/
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable Integer id) {
        problemService.deleteProblem(id);
        return Result.success();
    }

    /*添加题目*/
    @PostMapping("/add")
    public Result add(@RequestBody Problem problem) {
        try {
            problemService.insertProblem(problem);
        } catch (Exception e) {
            return Result.error("插入数据错误" + e);
        }
        return Result.success();
    }

    @PutMapping("/update/{id}")
    public Result update(@PathVariable Integer id, @RequestBody Problem problem) {
        try {
            // 设置ID
            problem.setId(id);
            problemService.updateProblem(problem);
        } catch (Exception e) {
            return Result.error("更新数据错误: " + e.getMessage());
        }
        return Result.success();
    }

}

